package com.nononsenseapps.feeder.ui

import android.content.Context
import android.os.Bundle
import android.widget.*
import com.nononsenseapps.feeder.db.ARG
import com.nononsenseapps.feeder.net.NetManager
import com.nononsenseapps.feeder.ui.base.CoroutineScopedActivity

class MutableServerActivity : CoroutineScopedActivity() {
    lateinit var serverName:EditText
    lateinit var serverList:ListView
    lateinit var addButton:Button
    lateinit var adapter : ServerAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        if (shouldBeFloatingWindow()) {
            setupFloatingWindow()
        }
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_mustable_server)
        serverName=findViewById(R.id.server_name)
        serverList=findViewById(R.id.server_list)
        addButton=findViewById(R.id.add_button)

        adapter = ServerAdapter(this)

        serverList.adapter=adapter

        serverList.setOnItemClickListener { _, view, position, _ ->
           val popupMenu = PopupMenu(this,view)
            popupMenu.menuInflater.inflate(R.menu.contextmenu_server_list,popupMenu.menu)
            popupMenu.setOnMenuItemClickListener { menuItem->
               when(menuItem.itemId){
                   R.id.action_delete->{
                       adapter.remove(adapter.getItem(position))
                       saveDate()
                   }
                   else->{}
               }
               true
            }
            popupMenu.show()
        }

        addButton.setOnClickListener {
            val newAddr = serverName.text.toString()
            if(newAddr.isEmpty() || adapter.serverList().contains(newAddr)) {
                return@setOnClickListener
            }
            adapter.add(newAddr)
            saveDate()
        }

        initData()

        intent.getStringExtra(ARG.LINK)?.let {newHost->
            val findHost = adapter.serverList().find { newHost.startsWith(it) }
            if(findHost == null)
                serverName.setText(newHost)
            else
                serverName.setText(findHost)
        }
    }

    private fun initData() {
       adapter.addAll(NetManager.mutableServerList)
    }

    private fun saveDate(){
        NetManager.mutableServerList = adapter.serverList()
    }

    class ServerAdapter(context: Context):ArrayAdapter<String>(context,R.layout.view_server,R.id.server_name){
       fun serverList():List<String>{
           val retList= ArrayList<String>()
           (0 until count).forEach {
               getItem(it)?.let { it1 -> retList.add(it1) }
           }
           return retList
       }
    }

}